package leaf.cloud.common.core;


import leaf.cloud.common.core.constant.Constants;
import leaf.cloud.common.core.enums.ReturnCode;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Result<T> {
    private static final long serialVersionUID = 1L;
    public static final int SUCCESS = Constants.SUCCESS;
    public static final int FAIL = Constants.FAIL;
    /**
     * 错误码.
     */
    private Integer code;
    /**
     * 提示信息.
     */
    private String msg;
    /**
     * 具体的内容.
     */
    private T data;
    /**
     * 时间戳
     */
    private Long timestamp;

    public Result() {
    }

    public Result(Integer code, String msg, Long timestamp, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.timestamp = timestamp;
    }

    private static <T> Result<T> restResult(int code, String msg, Long timestamp, T data) {
        return new Result<>(code, msg, timestamp, data);
    }

    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> success(T data) {
        return success(ReturnCode.SUCCESS.getMsg(), data);
    }

    public static <T> Result<T> success(String msg, T data) {
        return restResult(SUCCESS, msg, System.currentTimeMillis(), data);
    }

    public static <T> Result<T> fail() {
        return fail(FAIL, null);
    }

    public static <T> Result<T> fail(String msg) {
        return fail(FAIL, msg, null);
    }

    public static <T> Result<T> fail(Integer code, String msg) {
        return fail(code, msg, null);
    }

    public static <T> Result<T> fail(Integer code, String msg, T data) {
        return restResult(code, msg, System.currentTimeMillis(), data);
    }

    public static <T> Result<T> fail(ReturnCode returnCode) {
        if (null == returnCode) {
            return fail(FAIL, ReturnCode.FAIL.getMsg(), null);
        }
        return fail(returnCode.getCode(), returnCode.getMsg(), null);
    }

    public static <T> Result<T> error() {
        return error(null);
    }

    public static <T> Result<T> error(T data) {
        return error(ReturnCode.SERVER_ERROR.getCode(), ReturnCode.SERVER_ERROR.getMsg(), data);
    }

    public static <T> Result<T> error(String msg, T data) {
        return error(ReturnCode.SERVER_ERROR.getCode(), msg, data);
    }

    public static <T> Result<T> error(Integer code, String msg, T data) {
        return restResult(code, msg, System.currentTimeMillis(), data);
    }

    public static <T> Result<T> error(ReturnCode returnCode) {
        if (null == returnCode) {
            return fail(FAIL, ReturnCode.FAIL.getMsg(), null);
        }
        return fail(returnCode.getCode(), returnCode.getMsg(), null);
    }
}
